import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Tag, Row, Col, Typography, Form, Input, Select, Pagination, Tooltip, Modal, Tabs } from 'antd';
import { PlusOutlined, DeleteOutlined, SearchOutlined, EyeOutlined } from '@ant-design/icons';
import { message } from 'antd';
import { Knowledge, KnowledgeItem } from '../store/vectorTypes';
import VectorItemForm from './VectorItemForm';
import { knowledgeItemStore } from '../store/knowledgeItemStore';
import { observer } from 'mobx-react';

const { Option } = Select;
const { TabPane } = Tabs;
const { Text } = Typography;

// 分片接口
interface VectorSlice {
  id: string;
  itemId: string;
  itemName: string;
  content: string;
  index: number;
  vectorId: string;
  dimension: number;
  createTime: string;
}

interface VectorItemModalProps {
  visible: boolean;
  onCancel: () => void;
  currentTable: Knowledge | null;
  vector: any; // 添加vector属性
}

const VectorItemModal: React.FC<VectorItemModalProps> = observer(({ visible, onCancel, currentTable, vector }) => {
  const [activeTab, setActiveTab] = useState('items');
  const [slices, setSlices] = useState<VectorSlice[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [sliceCurrentPage, setSliceCurrentPage] = useState(1);
  const [pageSize] = useState(12);
  const [total, setTotal] = useState(0);
  const [sliceTotal, setSliceTotal] = useState(0);
  const [filterForm] = Form.useForm();
  const [sliceFilterForm] = Form.useForm();
  const [selectedItem, setSelectedItem] = useState<string | null>(null);
  const [isItemFormVisible, setIsItemFormVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  // 筛选条件
  const [filters, setFilters] = useState<{
    name: string;
    isEmbedded: number | undefined;
  }>({
    name: '',
    isEmbedded: undefined,
  });

  // 分片筛选条件
  const [sliceFilters, setSliceFilters] = useState<{
    itemName: string;
  }>({
    itemName: '',
  });

  // 获取知识条目数据
  const fetchItems = async (page = 1, filters: { name: string; isEmbedded: number | undefined } | null = null) => {
    const currentFilters = filters || { name: '', isEmbedded: undefined };
    if (currentTable && currentTable.id) {
      setLoading(true);
      try {
        const params: any = {
          pageNo: page,
          pageSize,
        };
        
        // 处理筛选条件
        if (currentFilters.name) {
          params.keyword = currentFilters.name;
        }
        if (currentFilters.isEmbedded !== undefined) {
          params.isEmbedded = currentFilters.isEmbedded ? 1 : 0;
        }
        
        await knowledgeItemStore.fetchKnowledgeItems(currentTable.id, params);
        setTotal(knowledgeItemStore.total);
        setCurrentPage(knowledgeItemStore.currentPage);
      } catch (error) {
        console.error('获取知识条目失败:', error);
        message.error('获取知识条目失败');
      } finally {
        setLoading(false);
      }
    }
  };

  useEffect(() => {
    if (visible && currentTable) {
      fetchItems(1, { name: '', isEmbedded: undefined });

      // 重置分页和筛选条件
      setCurrentPage(1);
      setSliceCurrentPage(1);
      filterForm.resetFields();
      sliceFilterForm.resetFields();
      setSelectedItem(null);

      // 模拟分片数据 (实际项目中应通过API获取)
      const mockSlices: VectorSlice[] = [];
      knowledgeItemStore.knowledgeItems.forEach(item => {
        for (let i = 0; i < Math.min(item.sliceCount || 5, 5); i++) {
          mockSlices.push({
            id: `slice-${item.id}-${i}`,
            itemId: item.id,
            itemName: item.name,
            content: `这是"${item.name}"的第${i + 1}个分片内容，包含了文档的一部分内容。这里是示例文本，实际内容会根据文档切片算法生成。`,
            index: i,
            vectorId: `vector-${item.id}-${i}`,
            dimension: item.dimension,
            createTime: item.createTime,
          });
        }
      });

      setSlices(mockSlices);
      setSliceTotal(mockSlices.length);
    }
  }, [visible, currentTable, filterForm, sliceFilterForm]);

  // 处理筛选
  const handleFilter = (values: any) => {
    setFilters(values);
    setCurrentPage(1);
    // 调用API重新获取数据
    fetchItems(1, values);
  };



  // 处理分片筛选
  const handleSliceFilter = (values: any) => {
    setSliceFilters(values);
    setSliceCurrentPage(1);
    // 重新获取分片数据
    fetchFilteredSlices(values, 1, pageSize);
  };

  // 获取筛选后的分片数据
  const fetchFilteredSlices = async (filters: any, page: number, pageSize: number) => {
    // 实际项目中应该调用API获取筛选后的分片数据
    // 暂时使用本地筛选模拟
    const filteredSlices = slices.filter(slice => {
      return (
        (!filters.itemName || slice.itemName.toLowerCase().includes(filters.itemName.toLowerCase())) &&
        (!selectedItem || slice.itemId === selectedItem)
      );
    });

    setSliceTotal(filteredSlices.length);
    // 模拟分页
    const startIndex = (page - 1) * pageSize;
    const paginatedSlices = filteredSlices.slice(startIndex, startIndex + pageSize);
    setSlices(paginatedSlices);
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    setCurrentPage(page);
    // 调用API获取对应页的数据
    fetchItems(page, filters);
  };

  // 处理分片分页变化
  const handleSlicePageChange = (page: number, pageSize?: number) => {
    setSliceCurrentPage(page);
    // 获取对应页的分片数据
    fetchFilteredSlices(sliceFilters, page, pageSize || 12);
  };

  const handleAddItem = () => {
    setIsItemFormVisible(true);
  };

  const handleItemFormSubmit = async (values: any) => {
    message.success('知识条目添加成功！');
    setIsItemFormVisible(false);

    // 重新获取数据列表
    await fetchItems(currentPage, filters);
  };

  const handleViewItem = (item: KnowledgeItem) => {
    setSelectedItem(item.id);
    setActiveTab('slices');
    sliceFilterForm.setFieldsValue({ itemName: item.name });
    handleSliceFilter({ itemName: item.name });
  };

  const handleDeleteItem = async (item: KnowledgeItem) => {
    console.log(item)
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除知识库条目"${item.title || item.name}"吗？此操作不可恢复。`,
      okText: '确认删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        await knowledgeItemStore.deleteKnowledgeItem(item.id);
        // 删除成功后重新获取数据
        await fetchItems(currentPage, filters);
      },
    });
  };

  const handleViewSlice = (slice: VectorSlice) => {
    message.info('查看分片详情功能待实现');
  };

  const handleDeleteSlice = (slice: VectorSlice) => {
    message.info('删除分片功能待实现');
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    if (key === 'items') {
      setSelectedItem(null);
    }
  };

  return (
    <>
      <Modal
        title={`${currentTable?.name || ''} - 知识库管理`}
        open={visible}
        onCancel={onCancel}
        maskClosable={false}
        keyboard={false}
        footer={null}
        width="90%"
        style={{ top: 20 }}
        bodyStyle={{
          maxHeight: 'calc(100vh - 120px)',
          overflowY: 'auto',
          padding: '24px'
        }}
      >
        <Tabs activeKey={activeTab} onChange={handleTabChange} type='card' centered>
          <TabPane tab="条目管理" key="items">
            {/* 条目筛选表单 */}
            <Card style={{ marginBottom: 16 }}>
                              <Form
                  form={filterForm}
                  layout="inline"
                  onFinish={handleFilter}
                  initialValues={filters}
                  onValuesChange={(changedValues, allValues) => {
                    // 当筛选条件变化时，如果两个字段都为空，则重置为初始状态
                    if (!allValues.name && allValues.isEmbedded === undefined) {
                      setFilters({ name: '', isEmbedded: undefined });
                    }
                  }}
                >
                <Form.Item name="name" label="条目名称">
                  <Input placeholder="请输入条目名称" allowClear />
                </Form.Item>
                <Form.Item name="isEmbedded" label="嵌入状态">
                  <Select style={{ width: 120 }} allowClear placeholder="请选择状态">
                    <Option value={true}>已嵌入</Option>
                    <Option value={false}>未嵌入</Option>
                  </Select>
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading}>
                    搜索
                  </Button>
                  <Button 
                    onClick={() => {
                      filterForm.resetFields();
                      setFilters({ name: '', isEmbedded: undefined });
                      fetchItems(1, { name: '', isEmbedded: undefined });
                      setCurrentPage(1);
                    }} 
                    style={{ marginLeft: 8 }}
                  >
                    重置
                  </Button>
                  <Button type="primary" icon={<PlusOutlined />} onClick={handleAddItem} style={{ marginLeft: 12 }}>
                    新建条目
                  </Button>
                </Form.Item>
              </Form>
            </Card>

            <Row gutter={[24, 24]}>
              {knowledgeItemStore.knowledgeItems.length === 0 ? (
                <Col span={24} style={{ textAlign: 'center', color: '#999', padding: '40px 0' }}>
                  <div style={{ fontSize: '16px', marginBottom: '8px' }}>暂无文件数据</div>
                  <div style={{ fontSize: '14px' }}>点击"新建条目"按钮添加文件</div>
                </Col>
              ) : (
                knowledgeItemStore.knowledgeItems.map((item) => (
                  <Col xs={24} sm={12} md={8} lg={6} xl={6} key={item.id}>
                    <Card
                      title={
                        <span style={{ fontWeight: 500 }}>
                          {item.title || item.name}
                        </span>
                      }
                      extra={
                        <Space size={2}>
                          <Tooltip title="查看分段">
                            <Button
                              type="text"
                              icon={<EyeOutlined />}
                              onClick={() => handleViewItem(item)}
                            />
                          </Tooltip>
                          <Tooltip title="删除">
                            <Button
                              type="text"
                              danger
                              icon={<DeleteOutlined />}
                              onClick={() => handleDeleteItem(item)}
                            />
                          </Tooltip>
                        </Space>
                      }
                      hoverable
                      style={{ minHeight: 220 }}
                    >
                      <div style={{ marginBottom: 8 }}>
                        <Tag color={item.isEmbedded ? 'success' : 'warning'}>
                          {item.isEmbedded ? '已嵌入' : '未嵌入'}
                        </Tag>
                        {item.fileFormat && (
                          <Tag color="blue">{item.fileFormat.toUpperCase()}</Tag>
                        )}
                      </div>
                      <div>
                        <b>摘要：</b>{item.summary}
                      </div>
                      <div>
                        <b>描述：</b>{item.description}
                      </div>
                      <div style={{ fontSize: '13px' }}>
                        <b>分段数量：</b>{item.sliceCount}
                      </div>
                      <div style={{ marginTop: 8, color: '#888', fontSize: '12px' }}>
                        <b>创建时间：</b>{item.createTime}
                      </div>
                    </Card>
                  </Col>
                ))
              )}
            </Row>

            {/* 分页组件 */}
            {total > 0 && (
              <div style={{
                marginTop: 16,
                display: 'flex',
                justifyContent: 'flex-end',
                padding: '0 24px'
              }}>
                <Pagination
                  current={currentPage}
                  pageSize={pageSize}
                  total={total}
                  onChange={handlePageChange}
                  showSizeChanger={false}
                  showTotal={(total) => `共 ${total} 条`}
                />
              </div>
            )}
          </TabPane>

          <TabPane tab="分段管理" key="slices">
            {/* 分片筛选表单 */}
            <Card style={{ marginBottom: 16 }}>
                              <Form
                  form={sliceFilterForm}
                  layout="inline"
                  onFinish={handleSliceFilter}
                  initialValues={sliceFilters}
                  onValuesChange={(changedValues, allValues) => {
                    // 当筛选条件变化时，如果字段为空，则重置为初始状态
                    if (!allValues.itemName) {
                      setSliceFilters({ itemName: '' });
                    }
                  }}
                >
                <Form.Item name="itemName" label="">
                  <Input placeholder="搜索条目" allowClear />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                  <Button 
                    onClick={() => {
                      sliceFilterForm.resetFields();
                      setSliceFilters({ itemName: '' });
                      fetchFilteredSlices({ itemName: '' }, 1, pageSize);
                      setSliceCurrentPage(1);
                    }} 
                    style={{ marginLeft: 8 }}
                  >
                    重置
                  </Button>
                  {selectedItem && (
                    <Button onClick={() => {
                      setSelectedItem(null);
                      sliceFilterForm.resetFields();
                      handleSliceFilter({});
                    }} style={{ marginLeft: 8 }}>
                      查看全部
                    </Button>
                  )}
                </Form.Item>
              </Form>
            </Card>

            <Row gutter={[24, 24]}>
              {slices.length === 0 ? (
                <Col span={24} style={{ textAlign: 'center', color: '#999', padding: '40px 0' }}>
                  <div style={{ fontSize: '16px', marginBottom: '8px' }}>暂无分段数据</div>
                  <div style={{ fontSize: '14px' }}>请先上传文件并进行分段处理</div>
                </Col>
              ) : (
                slices.map((slice) => (
                  <Col xs={24} sm={12} md={8} lg={6} xl={6} key={slice.id}>
                    <Card
                      title={
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <Text ellipsis={{ tooltip: slice.itemName }} style={{ fontWeight: 500 }}>
                            {slice.itemName}
                          </Text>
                          <div style={{ marginLeft: 4, fontWeight: 500, flexShrink: 0, color: '#1890ff' }}>
                            #{slice.index + 1}
                          </div>
                        </div>
                      }
                      extra={
                        <Space size={2}>
                          <Tooltip title="查看详情">
                            <Button
                              type="text"
                              icon={<EyeOutlined />}
                              onClick={() => handleViewSlice(slice)}
                            />
                          </Tooltip>
                          <Tooltip title="删除">
                            <Button
                              type="text"
                              danger
                              icon={<DeleteOutlined />}
                              onClick={() => handleDeleteSlice(slice)}
                            />
                          </Tooltip>
                        </Space>
                      }
                      hoverable
                      style={{ minHeight: 220 }}
                      bodyStyle={{ padding: '12px' }}
                    >
                      {slice.dimension && (
                        <div style={{ marginBottom: 8 }}>
                          <Tag color="blue">向量维度: {slice.dimension}</Tag>
                        </div>
                      )}
                      <div style={{
                        height: '120px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        display: '-webkit-box',
                        WebkitLineClamp: 5,
                        WebkitBoxOrient: 'vertical',
                        backgroundColor: '#f9f9f9',
                        padding: '8px',
                        borderRadius: '4px',
                        fontSize: '13px',
                        lineHeight: '1.6'
                      }}>
                        {slice.content}
                      </div>
                      <div style={{ marginTop: 8, color: '#888', fontSize: '12px' }}>
                        <b>创建时间：</b>{slice.createTime}
                      </div>
                    </Card>
                  </Col>
                ))
              )}
            </Row>

            {/* 分页组件 */}
            {sliceTotal > 0 && (
              <div style={{
                marginTop: 16,
                display: 'flex',
                justifyContent: 'flex-end',
                padding: '0 24px'
              }}>
                <Pagination
                  current={sliceCurrentPage}
                  pageSize={pageSize}
                  total={sliceTotal}
                  onChange={handleSlicePageChange}
                  showSizeChanger={false}
                  showTotal={(total) => `共 ${total} 条`}
                />
              </div>
            )}
          </TabPane>
        </Tabs>
      </Modal>

      {/* 新建知识条目表单 */}
      <VectorItemForm
        visible={isItemFormVisible}
        onCancel={() => setIsItemFormVisible(false)}
        onSubmit={handleItemFormSubmit}
        currentTable={currentTable}
        vector={vector}
      />
    </>
  );
});

export default VectorItemModal; 